"""
用来处理表格相关接口
"""
from openpyxl import load_workbook


def get_urls_from_excel(file_path):
    """
    读取表格获取表格中的链接信息，返回待检测的链接
    :param file_path: 表格路径
    :return: 待检测的链接字典
    """
    rb = load_workbook(file_path)
    rs = rb.worksheets[0]
    to_be_check_urls = []
    for row in rs.iter_rows(min_row=2):
        to_be_check_urls.append(row[2].value)
    return to_be_check_urls


def result_write_to_excel(file_path: str, result: dict):
    """
    将结果写入到表格中
    :param file_path: 表格路径
    :param result: 结果字典
    :return: None
    """
    rb = load_workbook(file_path)
    rs = rb.worksheets[0]
    for row in rs.iter_rows(min_row=2, values_only=False):
        last_cell = row[-1]
        new_cell = last_cell.offset(column=1)
        try:
            new_cell.value = result[row[2].value]
        except KeyError:
            new_cell.value = '无结果请确认'
        # 问题分类
        question = new_cell.value
        if 'Failed' in question:
            question_classify_cell = new_cell.offset(column=1)
            if '重定向' in question:
                question_classify_cell.value = '链接重定向问题'
            elif '未正确跳转到锚点' in question:
                question_classify_cell.value = '链接未跳转到正确锚点'
            elif '404' in question or '403' in question or '400' in question or '504' in question:
                question_classify_cell.value = '链接不存在'
            else:
                question_classify_cell.value = '待确认'

    rs['D1'] = '结果'
    rs['E1'] = '问题分类'
    rb.save(file_path)
